module CanCamel::Validators
  module GeneralValidators
    def presence(field:)
      raise ValidationError unless field.present?
    end

    def absence(field:)
      raise ValidationError if field.present?
    end

    def presence_of(fields:, args:, any: false, only: false, none: false)
      if [any, only, none].select(&:presence).count > 1
        raise ValidationError, 'only one of [any, only, none] could be supplied to presence_of'
      end

      only = 0 if none
      only = 1 if only && !only.is_a?(Fixnum)

      fields_present = fields.select { |x| args[x].present? }

      case
      when only
        return if fields_present.count == only
      when any
        return if fields_present.count > 0
      else
        return if fields_present.count == fields.count
      end
      raise ValidationError
    end

    def in(field:, array: [], empty: false)
      return if array.include? field
      return if empty && !field.present?
      raise ValidationError
    end

    def custom(field:, lambda:, empty: false)
      return if empty && !field.present?
      return if lambda.call(field)
      raise ValidationError
    end
  end
end
